<?php

namespace App\Service\OpenShop\SiteLocation;

use App\Enums\BaseErrorCode;
use App\Enums\OpenShop\InvestmentPromotion\SiteLocationEnum;
use App\Exceptions\Custom\ResponseHttpException;
use App\Http\Middleware\OpenShop\UserPermissionAuth;
use App\Models\Common\ConfigModel;
use App\Models\Common\ResourcesModel;
use App\Models\Cruise\CruiseOrderInputModel;
use App\Models\Cruise\CruiseTemplateModel;
use App\Models\OpenShop\Common\SiteLocationMallModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationHouseEvaluateModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Remote\Rms\RmsUserRemote;
use App\Service\Common\AreaService;
use App\Service\Cruise\Mission\CruiseOrderInputBaseService;
use App\Service\OpenShop\Feishu\BaseService;
use App\Service\OpenShop\Feishu\MessageSendService;
use App\Service\OpenShop\Feishu\OrganizationManageService;
use App\Support\CustomForm\AttributeCruiseSupport;
use App\Support\CustomForm\AttributeOpenShopSupport;
use App\Support\CustomForm\AttributeSupport;
use App\Support\CustomForm\ValidateSupport;
use App\Support\FeishuMsgSupport;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Kuafu\File\FileUtil;
use OSS\Core\OssException;

class SiteLocationInputService extends CruiseOrderInputBaseService
{
    private OpenShopSiteLocationModel $siteLocationModel;
    private int                       $userId;

    /**
     * 景区的各项满分
     */
    const JQ_SCORE_TYPES = [
        ['scenicScore', '景区评估', 40],
        ['streetScore', '商街评估', 30],
        ['shopScore', '铺位评估', 20],
        ['takeoutScore', '外卖评估', 10],
    ];

    public function __construct(string $orderNo, int $userId = 0)
    {
        $this->userId = $userId;

        $siteLocationModel = OpenShopSiteLocationModel::query()
                                                      ->where('orderNo', $orderNo)
            ->whereIn('source',
                [
                    OpenShopSiteLocationModel::SOURCE_OPEN_SHOP,
                    OpenShopSiteLocationModel::SOURCE_HOUSING
                ])
                                                      ->first();
        if (!$siteLocationModel) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "不存在的房源orderNo:{$orderNo}");
        }
        $this->siteLocationModel = $siteLocationModel;

        $sysTemplate = SiteLocationEnum::SHOP_MODEL_TYPE_TO_SYS_TEMPLATE[$siteLocationModel->shopModelType] ?? null;
        if ($sysTemplate === null) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null,
                "门店模型类型错误：{$orderNo} {$siteLocationModel->shopModelType}");
        }

        parent::__construct($this->siteLocationModel->id ?? 0, CruiseTemplateModel::TYPE_2, $sysTemplate);
    }

    /**
     * 初始化表单信息
     */
    public function initOrderInput(): void
    {
        $templateId = CruiseTemplateModel::query()
                                         ->where('type', $this->templateType)
                                         ->where('sysTemplate', $this->sysTemplate)
                                         ->where('status', CruiseTemplateModel::STATUS_ON)
                                         ->value('id') ?? 0;
        if (!$templateId) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "获取模板类型对应模板失败:{$this->templateType}");
        }

        // 幂等-不再创建
        if ($this->siteLocationModel->houseEvaluateStatus != SiteLocationEnum::HOUSE_EVALUATE_STATUS_DEFAULT) {
            return;
        }

        // 评估状态改为待提交
        $this->siteLocationModel->houseEvaluateStatus = SiteLocationEnum::HOUSE_EVALUATE_STATUS_WAIT;
        $this->siteLocationModel->save();

        parent::baseInitOrderInput($templateId);
    }

    /**
     * 获取当前处理人信息
     * @param int $status
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    private function getCurrentHandlerInfo(int $status): array
    {
        switch ($status) {
            case SiteLocationEnum::HOUSE_EVALUATE_STATUS_WAIT:
                $userIds = [(int)$this->siteLocationModel->createdByUid];
                break;
            case SiteLocationEnum::HOUSE_EVALUATE_STATUS_AUDIT:
                $userIds = json_decode(ConfigModel::query()
                                                  ->where('name', ConfigModel::SITE_MANAGER)
                                                  ->value('value'), true) ?? [];
                break;
            default:
                return ['userIds' => [(int)$this->siteLocationModel->createdByUid], 'userNames' => ''];
        }

        $userNames = collect(RmsUserRemote::getRmsUserByIds($userIds))->implode('username', ',');

        return ['userIds' => $userIds, 'userNames' => $userNames];
    }

    /**
     * 保存用户填写内容
     * @param string $field
     * @param $value
     * @return void
     * @throws Exception|GuzzleException
     */
    public function saveUserContentJson(string $field, $value): void
    {
        // 角色校验
        $handler = $this->getCurrentHandlerInfo($this->siteLocationModel->houseEvaluateStatus);
        if (!in_array($this->userId, $handler['userIds'])) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null,
                "您无权操作，当前处理人：{$handler['userNames']}");
        }

        //商场店特殊处理
        if ($this->siteLocationModel->shopModelType == SiteLocationEnum::SHOP_MODEL_TYPE_MALL) {
            if (in_array($field, ['shopNumImg', 'starImg'])) {
                ResourcesModel::moduleBusinessSingleResourcesUpdate(
                    ResourcesModel::MODULE_TYPE_SITE_MALL,
                    ResourcesModel::BUSINESS_SITE_LOCATION_MALL,
                    $field . $this->siteLocationModel->mallId,
                    0,
                    $value,
                );
            } elseif ($field == 'businessMap') {
                //生成图片
                $url = SiteLocationService::mapImageUrl(($value['longitude'] ?? '') ?: $this->siteLocationModel->longitude, ($value['latitude'] ?? '') ?: $this->siteLocationModel->latitude, ($value['name'] ?? '') ?: (string)$this->siteLocationModel->siteAddress, 630, 275);
                $png = sys_get_temp_dir() . '/' . Str::random() . '.png';
                (new Client())->get($url, [
                    'sink' => $png,
                ]);
                $file = FileUtil::uploadFile($png);
                @unlink($png);
                ResourcesModel::moduleBusinessSingleResourcesUpdate(
                    ResourcesModel::MODULE_TYPE_SITE_MALL,
                    ResourcesModel::BUSINESS_SITE_LOCATION_MALL,
                    'mapImage' . $this->siteLocationModel->mallId,
                    0,
                    [$file['path'] ?? '']
                );

                $this->siteLocationModel->update([
                    $field         => json_encode($value, JSON_UNESCAPED_UNICODE),
                    'mallAddress'  => $value['name'] ?? '',
                    'mallArea'     => $value['name'] ?? '',
                ]);
            } elseif ($field == 'businessArea') {
                $areaArr = explode('-', $value);
                $this->siteLocationModel->update([
                    $field         => $value,
                    'mallProvince' => $areaArr[0] ?? '',
                    'mallCity'     => $areaArr[1] ?? '',
                    'mallDistrict' => $areaArr[2] ?? '',
                ]);
            } elseif ($field == 'shopTotalNum') {
                if ($this->siteLocationModel->gourmetShopNum > 0 && $value > 0) {
                    $arr = [
                        $field             => $value,
                        'gourmetShopRatio' => round($this->siteLocationModel->gourmetShopNum / $value * 100, 2),
                    ];
                } else {
                    $arr = [
                        $field => $value,
                    ];
                }
                $this->siteLocationModel->update($arr);
            } elseif ($field == 'gourmetShopNum') {
                if ($this->siteLocationModel->shopTotalNum > 0 && $value > 0) {
                    $arr = [
                        $field             => $value,
                        'gourmetShopRatio' => round($value / $this->siteLocationModel->shopTotalNum * 100, 2),
                    ];
                } else {
                    $arr = [
                        $field => $value,
                    ];
                }
                $this->siteLocationModel->update($arr);
            } else {
                $this->siteLocationModel->update([
                    $field => $value
                ]);
            }
            return;
        }

        // 状态校验
        if($this->siteLocationModel->clueStatus != OpenShopSiteLocationModel::CLUE_STATUS_4) {
            if ($this->siteLocationModel->houseEvaluateStatus != SiteLocationEnum::HOUSE_EVALUATE_STATUS_WAIT) {
                throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "表单状态错误");
            }
        }

        parent::baseSaveUserContentJson($field, $value);
    }

    /**
     * 获取项目input
     * @return array
     * @throws GuzzleException
     */
    public function getInputObjectFill(): array
    {

        $disable = false;
        $submit  = false;

        // 权限校验
        $handler = $this->getCurrentHandlerInfo($this->siteLocationModel->houseEvaluateStatus);
        if (!in_array($this->userId, $handler['userIds'])) {
            $disable = true;
        }

        if ($this->siteLocationModel->houseEvaluateStatus != SiteLocationEnum::HOUSE_EVALUATE_STATUS_WAIT) {
            $disable = true;
        }

        if ($this->userId == $this->siteLocationModel->createdByUid && $this->siteLocationModel->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_4) {
            $disable = false;
            $submit  = true;
        }

        if ($this->siteLocationModel->shopModelType == SiteLocationEnum::SHOP_MODEL_TYPE_MALL) {
            //商场单独表单
            $data = [
                'cruiseId' => $this->siteLocationModel->id,
                'lists'    => SiteLocationMallService::createdMallJudge($this->siteLocationModel),
            ];
            $data['jumpType'] = 'mall';
        } else {
            $data = parent::baseGetInputObjectFill($disable);
            $data['jumpType'] = 'house';
        }
        $data['submit'] = in_array($this->userId, $handler['userIds']) || $submit;  // 表单提交权限


        $data['audit'] = in_array($this->userId,
            $this->getCurrentHandlerInfo(SiteLocationEnum::HOUSE_EVALUATE_STATUS_AUDIT)['userIds']); // 审核权限

        $data['status']    = $this->siteLocationModel->shopModelType == SiteLocationEnum::SHOP_MODEL_TYPE_MALL ? ($this->siteLocationModel->houseEvaluateStatus ?: 1) : $this->siteLocationModel->houseEvaluateStatus;
        $data['needAudit'] = $this->siteLocationModel->shopModelType == SiteLocationEnum::SHOP_MODEL_TYPE_SCENIC_SPOT_INSIDE;

        return $data;
    }

    /**
     * 用户提交表单
     * @return void
     */
    public function submitOrder(): void
    {

        // 角色校验
        $handler = $this->getCurrentHandlerInfo($this->siteLocationModel->houseEvaluateStatus);
        if (!in_array($this->userId, $handler['userIds'])) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null,
                "您无权操作，当前处理人：{$handler['userNames']}");
        }

        //商场店特殊处理
        if ($this->siteLocationModel->shopModelType == SiteLocationEnum::SHOP_MODEL_TYPE_MALL) {

            //计算商场等级
            $grade = $this->updateMallHouse();

            //获取房租性价比
            //$rentGrade = GuanyuanDataService::levelCityRentCostPerformance($this->siteLocationModel->orderNo);
            // 评估状态改为已完成
            $this->siteLocationModel->houseEvaluateStatus = SiteLocationEnum::HOUSE_EVALUATE_STATUS_FINISH;
            //$this->siteLocationModel->grade               = OpenShopSiteLocationModel::calcGrade($this->siteLocationModel->score);
            $this->siteLocationModel->shopGrade           = $grade['shopGrade'];
            $this->siteLocationModel->mallGrade           = $grade['mallGrade'];
            $this->siteLocationModel->clueStatus          = $this->afterSubmitClueStatus(0);
            $this->siteLocationModel->handler             = implode(',', $handler['userIds']);
            $this->siteLocationModel->save();
            $this->fsHouseClue();
            return;
        }


        // 状态校验
        if ($this->siteLocationModel->houseEvaluateStatus != SiteLocationEnum::HOUSE_EVALUATE_STATUS_WAIT) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "表单状态错误");
        }

        parent::baseSubmitOrder();

        if ($this->siteLocationModel->shopModelType == SiteLocationEnum::SHOP_MODEL_TYPE_SCENIC_SPOT_INSIDE) {

            // 评估状态改为审核中
            $this->siteLocationModel->houseEvaluateStatus = SiteLocationEnum::HOUSE_EVALUATE_STATUS_AUDIT;
            $this->siteLocationModel->clueStatus          = OpenShopSiteLocationModel::CLUE_STATUS_13;
            $this->siteLocationModel->handler             = implode(',', ConfigModel::getManager(ConfigModel::SITE_MANAGER));
            $this->siteLocationModel->save();

            // 审核 - 推送飞书通知给赤瞳进行审核
            $this->fsWaitAudit();
        } else {

            $scores = (new SiteLocationInputService($this->siteLocationModel->orderNo))->positionScores(null)[0];

            //获取房租性价比
            $rentGrade = GuanyuanDataService::levelCityRentCostPerformance($this->siteLocationModel->orderNo);
            // 评估状态改为已完成
            $this->siteLocationModel->houseEvaluateStatus = SiteLocationEnum::HOUSE_EVALUATE_STATUS_FINISH;
            $this->siteLocationModel->score               = array_sum($scores);
            $this->siteLocationModel->grade               = OpenShopSiteLocationModel::calcGrade($this->siteLocationModel->score);
            $this->siteLocationModel->shopGrade           = OpenShopSiteLocationModel::calcShopGrade($this->siteLocationModel->score, $rentGrade);
            $this->siteLocationModel->clueStatus          = $this->afterSubmitClueStatus($this->siteLocationModel->shopGrade);
            $this->siteLocationModel->handler             = implode(',', $handler['userIds']);
            $this->siteLocationModel->save();

            // 后续流程
            $this->fsHouseClue();
        }
    }

    /**
     * 提交后的clueStatus
     * @param int $shopGrade
     * @return int
     */
    private function afterSubmitClueStatus(int $shopGrade): int
    {
        if ($this->siteLocationModel->developConsultantId > 0) {
            $clueStatus = OpenShopSiteLocationModel::CLUE_STATUS_2;
        } else {
            $clueStatus = OpenShopSiteLocationModel::CLUE_STATUS_1;
        }

        // 不合格房源，直接关闭
        // 选址2.2.6优化关闭这个逻辑
        //        if ($shopGrade == OpenShopSiteLocationModel::HOUSE_SHOP_GRADE_E) {
        //            $clueStatus = OpenShopSiteLocationModel::CLUE_STATUS_0;
        //        }

        return $clueStatus;
    }

    /**
     * 审核表单输出
     * @return array[]
     */
    public function auditForm(): array
    {
        // 角色校验
        $handler = $this->getCurrentHandlerInfo($this->siteLocationModel->houseEvaluateStatus);
        if (!in_array($this->userId, $handler['userIds'])) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null,
                "您无权操作，当前处理人：{$handler['userNames']}");
        }

        $lists = [];

        $scoreTypes = self::JQ_SCORE_TYPES;

        foreach ($scoreTypes as $scoreType) {

            $lists[] = AttributeCruiseSupport
                ::getInstance($scoreType[0], AttributeSupport::INPUT_TYPE_NUMBER, $scoreType[1])
                ->setValidateRules(ValidateSupport::getInstance(true)->setContentLength(0, $scoreType[2]))
                ->setCustomAttribute(["placeholder", "请输入评分，最高{$scoreType[2]}分"])
                ->build();
        }

        $lists[] = AttributeCruiseSupport::getInstance('cpzdf', AttributeSupport::INPUT_TYPE_NUMBER, '测评总得分')
                                         ->setValidateRules(ValidateSupport::getInstance(false))
                                         ->setCustomAttribute(['disabled', true])
                                         ->build();

        $lists[] = AttributeCruiseSupport::getInstance('fzje', AttributeSupport::INPUT_TYPE_NUMBER, '房租金额')
                                         ->setValidateRules(ValidateSupport::getInstance(false))
                                         ->setCustomAttribute(['disabled', true], ['unit', '元/月'], ['isMoney', true])
                                         ->setValue((int)($this->siteLocationModel->clueRent / 12))
                                         ->build();

        $lists[] = AttributeCruiseSupport::getInstance('rentGrade', AttributeSupport::INPUT_TYPE_SELECT, '房租性价比')
                                         ->setValidateRules(ValidateSupport::getInstance(true))
                                         ->setCustomAttribute([
                                             'options',
                                             AttributeOpenShopSupport::setSelectOptions(SiteLocationEnum::COST_PERFORMANCES)
                                         ])->build();

        $lists[] = AttributeCruiseSupport::getInstance('content', AttributeSupport::INPUT_TYPE_TEXT, '房源测评总结')
                                         ->setValidateRules(ValidateSupport::getInstance(true)
                                                                           ->setContentLength(0, 1000))
                                         ->setCustomAttribute(["placeholder", "请输入分析与建议"])
                                         ->build();

        return ['form' => $lists];
    }

    /**
     * 审核
     * @param array $data
     * @return void
     */
    public function audit(array $data): void
    {
        // 状态校验
        if ($this->siteLocationModel->houseEvaluateStatus != SiteLocationEnum::HOUSE_EVALUATE_STATUS_AUDIT) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "表单状态错误");
        }

        // 角色校验
        $handler = $this->getCurrentHandlerInfo($this->siteLocationModel->houseEvaluateStatus);
        if (!in_array($this->userId, $handler['userIds'])) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null,
                "您无权操作，当前处理人：{$handler['userNames']}");
        }
        $this->siteLocationModel->houseEvaluateStatus = SiteLocationEnum::HOUSE_EVALUATE_STATUS_FINISH;
        $this->siteLocationModel->score               = $data['scenicScore'] + $data['streetScore'] + $data['shopScore'] + $data['takeoutScore'];
        $this->siteLocationModel->grade               = OpenShopSiteLocationModel::calcGrade($this->siteLocationModel->score);
        $this->siteLocationModel->shopGrade           = OpenShopSiteLocationModel::calcShopGrade($this->siteLocationModel->score, $data['rentGrade']);
        $this->siteLocationModel->clueStatus          = $this->afterSubmitClueStatus($this->siteLocationModel->shopGrade);
        $this->siteLocationModel->handler             = $this->siteLocationModel->developConsultantId;
        $this->siteLocationModel->save();

        (new OpenShopSiteLocationHouseEvaluateModel([
            'orderNo'      => $this->siteLocationModel->orderNo,
            'scenicScore'  => $data['scenicScore'],
            'streetScore'  => $data['streetScore'],
            'shopScore'    => $data['shopScore'],
            'takeoutScore' => $data['takeoutScore'],
            'rentGrade'    => $data['rentGrade'],
            'content'      => $data['content'],
        ]))->addData();

        // 后续流程
        $this->fsHouseClue();

        // 审核完成通知
        $this->fsFinishAudit();
    }

    /**
     * 评分结果页
     * @return array
     */
    public function result(): array
    {
        $provinceManager    = OrganizationManageService::getProvinceInfoByProvinceCode($this->siteLocationModel->provinceCode);
        $provinceManagerUid = $provinceManager["operationUid"] ?? 0;
        $isProvinceManager  = $provinceManagerUid == $this->userId;
        $isManager          = $this->siteLocationModel->developConsultantId > 0 && $this->siteLocationModel->developConsultantId == $this->userId;

        //商场
        if ($this->siteLocationModel->shopModelType == SiteLocationEnum::SHOP_MODEL_TYPE_MALL) {
            return $this->mallResult($isProvinceManager, $isManager);
        }

        // 状态校验
        if ($this->siteLocationModel->houseEvaluateStatus != SiteLocationEnum::HOUSE_EVALUATE_STATUS_FINISH) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "评估未完成，获取结果失败");
        }

        // 评估审核内容
        $evaluate = OpenShopSiteLocationHouseEvaluateModel::getData($this->siteLocationModel->orderNo);

        list($evaluateScore, $baseScore, $remarks) = $this->positionScores($evaluate);
        $baseScore = $baseScore + ['房租评估' => 40];

        // 房租性价比
        $rentGrade = GuanyuanDataService::levelCityRentCostPerformance($this->siteLocationModel->orderNo);
        if ($rentGrade == SiteLocationEnum::COST_PERFORMANCE_HIGH) {
            $rentScore = 36;
        } elseif ($rentGrade == SiteLocationEnum::COST_PERFORMANCE_MEDIUM) {
            $rentScore = 32;
        } else {
            $rentScore = 20;
        }

        // 分析与建议
        $advice = collect($remarks)
            ->map(function ($item, $title) {
                return [
                    'title'  => $title,
                    'remark' => collect($item)->implode('；'),
                ];
            })
            ->values();
        if ($evaluate) {
            $advice->add(['title' => '综合评估', 'remark' => $evaluate->content]);
        }

        $shopModelTypeText = SiteLocationEnum::SHOP_MODEL_TYPE_MAPPING[$this->siteLocationModel->shopModelType] ?? '';

//        if ($this->siteLocationModel->shopModelType == SiteLocationEnum::SHOP_MODEL_TYPE_SCENIC_SPOT_INSIDE) {
//            $rentGrade = $evaluate->rentGrade ?? SiteLocationEnum::COST_PERFORMANCE_LOW;
//        }

        $manager = [];
        ConfigModel::query()
            ->where('module', 'siteLocation')
            ->whereIn('name', [ConfigModel::SITE_SUPER_ADMIN, ConfigModel::SITE_MANAGER])
            ->get()
            ->each(function ($item) use (&$manager) {
                $manager = array_merge($manager, json_decode($item->value));
            });

        $level = $this->siteLocationModel->cityType;
        $levelText = SiteLocationEnum::CITY_TYPE_LEVEL_TEXT[$level] ?? '';

        $standard = GuanyuanDataService::levelCityRentRange($levelText);

        return [
            'siteId'            => $this->siteLocationModel->id,
            'score'             => $this->siteLocationModel->score,
            'modelGrade'        => $this->siteLocationModel->gradeText,  //评估等级
            'rentGrade'         => SiteLocationEnum::COST_PERFORMANCES[$this->siteLocationModel->rentGrade] ?? '-',
            'grade'             => $this->siteLocationModel->shopGrade,
            'shopGradeText'     => OpenShopSiteLocationModel::HOUSE_SHOP_GRADE_SIFT_MAPPING[$this->siteLocationModel->shopGrade] ?? '-',
            'charts'            => [
                [
                    'title' => $shopModelTypeText . '评分',
                    'lists' => collect($evaluateScore + ['房租评估' => $rentScore])->map(function ($value, $text) use (
                        $baseScore
                    ) {
                        return [
                            'text'     => $text,
                            'value'    => $value,
                            'maxValue' => $baseScore[$text] ?? 0,
                        ];
                    })->values()->toArray(),
                ],
                [
                    'title' => '房源模式基础评分',
                    'lists' => collect($baseScore)->map(function ($value, $text) {
                        return [
                            'text'  => $text,
                            'value' => floor($value * 0.75),
                        ];
                    })->values()->toArray(),
                ],
            ],
            'advice'            => $advice,
            "isProvinceManager" => $isProvinceManager,
            "isManager"         => $isManager,
            'clueStatus'        => $this->siteLocationModel->clueStatus,
            'isShowUpdate'      => in_array($this->userId, $manager),
            'updateInfo'        => [
                'orderNo'   => $this->siteLocationModel->orderNo,
                'scope'     => $this->siteLocationModel->score,
                'grade'     => $this->siteLocationModel->grade,
                'rentGrade' => $this->siteLocationModel->rentGrade,
                'rent'      => $this->siteLocationModel->clueRent,
                'shopGrade' => $this->siteLocationModel->shopGrade,
                'cityGrade' => $levelText,
                'rentDemo'  => $standard['minFourNumber'] . '-' . $standard['maxFourNumber']
            ]
        ];
    }

    /**
     * 获取评估分数、评估基础分
     * @return array[]
     */
    private function positionScores(?OpenShopSiteLocationHouseEvaluateModel $siteLocationHouseEvaluateModel): array
    {
        $scores    = [];
        $maxScores = [];
        $remarks   = [];

        $lists = parent::baseGetInputObjectFill()['lists'];
        foreach ($lists as $projects) {
            $positionName             = $projects['positionName'];
            $scores[$positionName]    = 0;
            $maxScores[$positionName] = 0;
            $remarks[$positionName]   = [];

            foreach ($projects['projects'] as $obj) {

                if ($obj['inputType'] == AttributeSupport::INPUT_TYPE_SELECT) {

                    $options = collect($obj['customAttributes']['options'])->sortByDesc('score')->keyBy('value');

                    // 最高分
                    $maxScores[$positionName] += ($options->first()['score'] ?? 0);

                    // 选中项加分
                    if ($obj['value'] !== null) {

                        $score                 = $options[$obj['value']]['score'] ?? 0;
                        $scores[$positionName] += $score;

                        $remarks[$positionName][] = $options[$obj['value']]['remark'] ?? '';
                    }
                }

                if ($obj['inputType'] == AttributeSupport::INPUT_TYPE_SELECT_MULTIPLE) {

                    $options = collect($obj['customAttributes']['options'])->keyBy('value');

                    // 最高分 - 合计
                    $maxScores[$positionName] += (int)$options->sum('score');

                    // 选中项加分
                    if ($obj['value']) {
                        foreach ($obj['value'] as $val) {
                            $score                    = $options[$val]['score'] ?? 0;
                            $scores[$positionName]    += $score;
                            $remarks[$positionName][] = $options[$val]['remark'] ?? '';
                        }
                    }
                }
            }
        }

        // 有房源评估记录的，直接取记录（景区店）
        if ($siteLocationHouseEvaluateModel) {
            $scores    = [];
            $maxScores = [];

            foreach (self::JQ_SCORE_TYPES as $v) {
                list($field, $name, $score) = $v;

                $scores[$name]    = $siteLocationHouseEvaluateModel[$field] ?? 0;
                $maxScores[$name] = $score;
            }
        }

        return [$scores, $maxScores, $remarks];
    }

    /**
     * 推动后续流程
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function fsHouseClue(): void
    {
        // 关闭的不处理
        if ($this->siteLocationModel->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_0) {
            return;
        }

        //发送飞书消息
        if ($this->siteLocationModel->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_1) {
            $examine        = ConfigModel::query()
                                         ->where('module', 'siteLocation')
                                         ->where('name', ConfigModel::SITE_MANAGER)
                                         ->value('value');
            $provinceInfoBy = OrganizationManageService::getProvinceInfoByProvinceCode($this->siteLocationModel->provinceCode);
            FeishuMsgSupport::getInstance("有新的房源线索待分配，请注意",
                array_merge([$provinceInfoBy["operationUid"]], json_decode($examine)))
                            ->setContent(
                                ["name" => "房源所在区域", "value" => $this->siteLocationModel->cityArea],
                                //["name" => "任务处理角色", "value" => "省区负责人"],  //会签模式  职位不能写死
                                ["name" => "任务名称", "value" => "房源线索调查"],
                                //["name" => "任务处理人", "value" => $provinceInfoBy["operationName"] ?? ""],
                                ["name" => "任务创建时间", "value" => formatDate(time())],
                            )
                            ->msgSend(["path" => "pages/house-source/add-source?id={$this->siteLocationModel->id}"]);
        } else {

            $userInfo = RmsUserRemote::getRmsUserByIds([$this->siteLocationModel->createdByUid])[0];
            $userName = $userInfo['username'] ?? '';

            FeishuMsgSupport::getInstance("您有一条房源勘址任务待处理！", [$this->siteLocationModel->createdByUid])
                            ->setContent(
                                ["name" => "房源所在区域", "value" => $this->siteLocationModel->cityArea],
                                ["name" => "任务处理角色", "value" => "选址顾问"],
                                ["name" => "任务名称", "value" => "房源线索调查"],
                                ["name" => "任务处理人", "value" => $userName],
                                ["name" => "任务创建时间", "value" => formatDate(time())]
                            )
                            ->msgSend(["path" => "pages/house-source/add-source?id={$this->siteLocationModel->id}"]);
        }
    }

    /**
     * 待审批推送
     * @return void
     */
    private function fsWaitAudit(): void
    {
        // 审核 - 推送飞书通知给赤瞳进行审核
        $auditUids = json_decode(ConfigModel::query()
                                            ->where('name', ConfigModel::SITE_MANAGER)
                                            ->value('value'), true);

        $userInfos = collect(RmsUserRemote::getRmsUserByIds(array_merge($auditUids, [$this->siteLocationModel->createdByUid])))->keyBy('id');
        $createdFeishuId  = $userInfos[$this->siteLocationModel->createdByUid]['feishuUserId'] ?? '';

        // 发送模板相关信息
        $template          = file_get_contents(resource_path('OpenShop/feishu/notifyTemplate/waitAuditHouseEvaluate.json'));
        $shopModelTypeText = SiteLocationEnum::SHOP_MODEL_TYPE_MAPPING[$this->siteLocationModel->shopModelType] ?? '';

        $createdAt = $this->siteLocationModel->createdAt->toDateTimeString();
        if ($this->siteLocationModel->houseEvaluateRel) {
            $taskCreatedAt = $this->siteLocationModel->houseEvaluateRel->createdAt->toDateTimeString() ?? '';
        } else {
            $taskCreatedAt = date('Y-m-d H:i:s');
        }
        $url = BaseService::getHouseEvaluateDetailUrl($this->siteLocationModel->id);

        $templateJson = json_decode(sprintf($template, $this->siteLocationModel->cityArea, $shopModelTypeText,
            $createdFeishuId, $createdAt, $taskCreatedAt, $url), true);

        foreach ($auditUids as $auditUid) {
            $receiverFeishuId = $userInfos[$auditUid]['feishuUserId'] ?? '';

            Log::info("fsWaitAudit Request: {$this->siteLocationModel->orderNo}", $templateJson);

            $res = MessageSendService::sendMessage($receiverFeishuId, 'user_id', $templateJson,
                'interactive', UserPermissionAuth::MODULE_OPEN_SHOP);

            Log::info("fsWaitAudit Response: {$this->siteLocationModel->orderNo}", (array)$res);
        }
    }

    /**
     * 审核完毕发送
     * @return void
     */
    private function fsFinishAudit(): void
    {
        $userInfos        = collect(RmsUserRemote::getRmsUserByIds([$this->siteLocationModel->createdByUid]))->keyBy('id');
        $receiverFeishuId = $userInfos[$this->siteLocationModel->createdByUid]['feishuUserId'] ?? '';

        $template          = file_get_contents(resource_path('OpenShop/feishu/notifyTemplate/finishAuditHouseEvaluate.json'));
        $shopModelTypeText = SiteLocationEnum::SHOP_MODEL_TYPE_MAPPING[$this->siteLocationModel->shopModelType] ?? '';

        $taskFinishAt = date('Y-m-d H:i:s');
        if ($this->siteLocationModel->houseEvaluateRel) {
            $taskCreatedAt = $this->siteLocationModel->houseEvaluateRel->createdAt->toDateTimeString() ?? '';
        } else {
            $taskCreatedAt = date('Y-m-d H:i:s');
        }
        $url = BaseService::getHouseEvaluateDetailUrl($this->siteLocationModel->id);

        $templateJson = json_decode(vsprintf($template, [
            $this->siteLocationModel->cityArea,
            $shopModelTypeText,
            $this->siteLocationModel->siteAddress,
            $this->siteLocationModel->score,
            OpenShopSiteLocationModel::HOUSE_GRADE_SIFT_MAPPING[$this->siteLocationModel->grade] ?? '',
            $this->siteLocationModel->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_0 ? '不通过' : '通过',
            $taskCreatedAt,
            $taskFinishAt,
            $url
        ]), true);

        Log::info("fsFinishAudit Request: {$this->siteLocationModel->orderNo}", $templateJson);

        $res = MessageSendService::sendMessage($receiverFeishuId, 'user_id', $templateJson,
            'interactive', UserPermissionAuth::MODULE_OPEN_SHOP);

        Log::info("fsFinishAudit Response: {$this->siteLocationModel->orderNo}", (array)$res);
    }

    /**
     * 修改评估报告
     * @param $params
     * @return bool
     * @throws GuzzleException
     */
    public function reportUpdate($params): bool
    {
        $manager = [];
        ConfigModel::query()
            ->where('module', 'siteLocation')
            ->whereIn('name', [ConfigModel::SITE_SUPER_ADMIN, ConfigModel::SITE_MANAGER])
            ->get()
            ->each(function ($item) use (&$manager) {
                $manager = array_merge($manager, json_decode($item->value));
            });

        if (!in_array($this->userId, $manager)) {
            return false;
        }
        if (isset($params['shopGrade']) && $this->siteLocationModel->shopGrade == OpenShopSiteLocationModel::HOUSE_SHOP_GRADE_E && $params['shopGrade'] != OpenShopSiteLocationModel::HOUSE_SHOP_GRADE_E) {
            $this->siteLocationModel->developConsultantId ? ($this->siteLocationModel->clueStatus = OpenShopSiteLocationModel::CLUE_STATUS_2) : ($this->siteLocationModel->clueStatus = OpenShopSiteLocationModel::CLUE_STATUS_1);
        }

        unset($params['orderNo']);

        if (isset($params['mallGradeValue'])) {
            $params['shopGrade'] = $params['mallGradeValue'];
            $params['mallGrade'] = OpenShopSiteLocationModel::HOUSE_SHOP_GRADE_SIFT_MAPPING[$params['mallGradeValue']] ?? '未评级';
        }

        if (isset($params['shopTotalNum']) && isset($params['gourmetShopNum'])) {
            if ($params['shopTotalNum'] > 0 && $params['gourmetShopNum'] > 0) {
                $params['gourmetShopRatio'] = round($params['gourmetShopNum'] / $params['shopTotalNum'] * 100, 2);
            } else {
                $params['gourmetShopRatio'] = 0;
            }
        }

        $this->siteLocationModel->update($params);

        if ($this->siteLocationModel->shopModelType == SiteLocationEnum::SHOP_MODEL_TYPE_MALL && !isset($params['mallGradeValue'])) {
            //更新房源等级
            $grade = $this->updateMallHouse();
            $this->siteLocationModel->update([
                'shopGrade' => $grade['shopGrade'],
                'mallGrade' => $grade['mallGrade'],
            ]);
        }

        $this->fsHouseClue();
        return true;
    }

    /**
     * 获得白名单的评估报告
     * @param $isProvinceManager
     * @param $isManager
     * @return array
     * @throws GuzzleException
     * @throws OssException
     */

    public function mallResult($isProvinceManager, $isManager): array
    {
        //获得观远数据
        try {
            $guanyuanData = GuanyuanDataService::getMallDataByMallId($this->siteLocationModel->mallId)[0] ?? [];
        } catch (\Exception $exception) {
            $guanyuanData = [];
        }
        $res          = true;
        //经纬度名称
        $lat   = 0;
        $lng   = 0;
        $title = '';
        if ([] == $guanyuanData) {
            //数据同步  从大表拿值
            $siteLocationMall = SiteLocationMallModel::query()
                ->where('mallId', $this->siteLocationModel->mallId)
                ->first();
            if ($siteLocationMall != null && $this->siteLocationModel->star <= 0) {
                $lat   = $siteLocationMall->lat;
                $lng   = $siteLocationMall->lng;
                $title = $siteLocationMall->area;
                $this->siteLocationModel->update([
                    'mallProvince'      => $siteLocationMall->province,
                    'mallCity'          => $siteLocationMall->city,
                    'mallDistrict'      => $siteLocationMall->district,
                    'mallArea'          => $siteLocationMall->area,
                    'mallAddress'       => $siteLocationMall->address,
                    'shopTotalNum'      => 0,
                    'goShoppingNum'     => 0,
                    'gourmetShopNum'    => 0,
                    'gourmetShopRatio'  => 0,
                    'star'              => $siteLocationMall->star,
                    'facilitiesRating'  => $siteLocationMall->facilitiesRating,
                    'environmentRating' => $siteLocationMall->environmentRating,
                    'serviceRating'     => $siteLocationMall->serviceRating,
                    'businessDistrict'  => $siteLocationMall->area,
                    'businessArea'      => $siteLocationMall->province . '-' . $siteLocationMall->city . '-' . $siteLocationMall->distinct,
                    'businessAddress'   => $siteLocationMall->address,
                ]);
            }
            if (!$this->siteLocationModel->mallStatus) {
                $res = false;
            }
        } elseif ($this->siteLocationModel->star <= 0) {
            $lat   = $guanyuanData['mall_y'] ?? 0;
            $lng   = $guanyuanData['mall_x'] ?? 0;
            $title = $guanyuanData['区域'] ?? '';

            $this->siteLocationModel->update([
                'mallProvince'      => $guanyuanData['省份'] ?? '',
                'mallCity'          => $guanyuanData['城市'] ?? '',
                'mallDistrict'      => $guanyuanData['区县'] ?? '',
                'mallArea'          => $guanyuanData['区域'] ?? '',
                'mallAddress'       => $guanyuanData['地址'] ?? '',
                'shopTotalNum'      => $guanyuanData['店铺总数'] ?? 0,
                'goShoppingNum'     => $guanyuanData['购物'] ?? 0,
                'gourmetShopNum'    => $guanyuanData['美食店铺数'] ?? 0,
                'gourmetShopRatio'  => round((float)($guanyuanData['美食店铺占比'] ?? 0) * 100, 2),
                'star'              => (float)($guanyuanData['星级'] ?? 0),
                'facilitiesRating'  => (float)($guanyuanData['设施评分'] ?? 0),
                'environmentRating' => (float)($guanyuanData['环境评分'] ?? 0),
                'serviceRating'     => (float)($guanyuanData['服务评分'] ?? 0),
                'businessDistrict'  => (string)($guanyuanData['区域'] ?? ''),
                'businessArea'      => (string)($guanyuanData['省份'] ?? '') . '-' . (string)($guanyuanData['城市'] ?? '') . '-' . (string)($guanyuanData['区县'] ?? ''),
                'businessAddress'   => (float)($guanyuanData['地址'] ?? 0),
            ]);
        }


        //根据经纬度生成&获得比例图片
        $imgUrl = (string)ResourcesModel::query()
            ->where('module', ResourcesModel::MODULE_TYPE_SITE_MALL)
            ->where('business', ResourcesModel::BUSINESS_SITE_LOCATION_MALL)
            ->where('name', 'mapImage' . $this->siteLocationModel->mallId)
            ->value('url');

        if (!mb_strlen($imgUrl)) {
            $url = SiteLocationService::mapImageUrl($lng ?: $this->siteLocationModel->longitude, $lat ?: $this->siteLocationModel->latitude, $title ?: (string)$this->siteLocationModel->siteAddress, 630, 275);
            $png = sys_get_temp_dir() . '/' . Str::random() . '.png';
            (new Client())->get($url, [
                'sink' => $png,
            ]);
            $file = FileUtil::uploadFile($png);
            @unlink($png);
            ResourcesModel::moduleBusinessSingleResourcesUpdate(
                ResourcesModel::MODULE_TYPE_SITE_MALL,
                ResourcesModel::BUSINESS_SITE_LOCATION_MALL,
                'mapImage' . $this->siteLocationModel->mallId,
                0,
                [$file['path'] ?? '']
            );
            $imgUrl = $file['url'];
        } else {
            $imgUrl = picturePath($imgUrl);
        }

        $manager = [];
        ConfigModel::query()
            ->where('module', 'siteLocation')
            ->whereIn('name', [ConfigModel::SITE_SUPER_ADMIN, ConfigModel::SITE_MANAGER])
            ->get()
            ->each(function ($item) use (&$manager) {
                $manager = array_merge($manager, json_decode($item->value));
            });

        $rent = SiteLocationEnum::COST_PERFORMANCES[GuanyuanDataService::levelCityRentCostPerformance($this->siteLocationModel->orderNo)] ?? '';

        return [
            'mallName'         => $this->siteLocationModel->mallName,
            'rent'             => "新商场未开业，从规划来看会是一个当地体量较大的商业，就当前城市而言，租金{$rent}，该项目未开业，与以往门店不同，有一定风险性，但外卖机会点大；铺位处于小吃餐饮层的话，有一定品牌氛围；主动线，展面良好，房租便宜情况下，可以尝试落位。",
            'province'         => $this->siteLocationModel->mallProvince,
            'city'             => $this->siteLocationModel->mallCity,
            'district'         => $this->siteLocationModel->mallDistrict,
            'area'             => $this->siteLocationModel->mallArea,
            'address'          => $this->siteLocationModel->mallAddress,
            'res'              => $res,
            'mallGrade'        => $this->siteLocationModel->mallGrade,
            'mallGradeValue'   => $this->siteLocationModel->shopGrade,
            'imgUrl'           => $imgUrl,
            'shopTotalNum'     => $this->siteLocationModel->shopTotalNum,
            'goShoppingNum'    => $this->siteLocationModel->goShoppingNum,
            'gourmetShopNum'   => $this->siteLocationModel->gourmetShopNum,
            'gourmetShopRatio' => $this->siteLocationModel->gourmetShopRatio,
            'charts'           => [
                'star'              => [
                    'text'  => '星级',
                    'value' => $this->siteLocationModel->star,
                ],
                'facilitiesRating'  => [
                    'text'  => '设施评分',
                    'value' => $this->siteLocationModel->facilitiesRating,
                ],
                'environmentRating' => [
                    'text'  => '环境评分',
                    'value' => $this->siteLocationModel->environmentRating,
                ],
                'serviceRating'     => [
                    'text'  => '服务评分',
                    'value' => $this->siteLocationModel->serviceRating,
                ],
            ],
            'isShowUpdate'      => in_array($this->userId, $manager) && !$this->siteLocationModel->isWhiteList,
            'updateType'        => $this->siteLocationModel->mallStatus ? 'open' : 'unopen',
            'isProvinceManager' => $isProvinceManager,
            'isManager'         => $isManager,
            'siteId'            => $this->siteLocationModel->id,
            'clueStatus'        => $this->siteLocationModel->clueStatus,
        ];
    }


    /**
     * 更新商场房源等级算法
     * @return array
     */
    public function updateMallHouse(): array
    {
        //根据商场ID获得榜单
        $siteLocationMall = SiteLocationMallModel::query()
            ->where('mallId', $this->siteLocationModel->mallId)
            ->first();

        if (null == $siteLocationMall && (strpos($this->siteLocationModel->mallId, 'MALL-') === false)) {
            return [
                'mallGrade' => 'C级',
                'shopGrade' => OpenShopSiteLocationModel::HOUSE_SHOP_GRADE_C
            ];
        }

        //判断走的是手加的还是数据库的
        if (strpos($this->siteLocationModel->mallId, 'MALL-') !== false) {
            //走的是手加的
            $isInput = true;
        } else {
            //数据库
            $isInput = false;
        }

        if (
            ($isInput || strpos($siteLocationMall->topList, '第一名'))
            && $this->siteLocationModel->star >= 4
            && $this->siteLocationModel->shopTotalNum >= 40
            && $this->siteLocationModel->facilitiesRating >= 7.8
            && $this->siteLocationModel->environmentRating >= 7.8
            && $this->siteLocationModel->serviceRating >= 7.8
            && $this->siteLocationModel->gourmetShopNum >= 38
            && $this->siteLocationModel->goShoppingNum >= 100
            && !strpos($this->siteLocationModel->mallName, '服饰')
            && !strpos($this->siteLocationModel->mallName, '华联')
            && !strpos($this->siteLocationModel->mallName, '甘家口')
        ) {
            return [
                'mallGrade' => 'S级',
                'shopGrade' => OpenShopSiteLocationModel::HOUSE_SHOP_GRADE_S
            ];
        }

        if (
            (($isInput || strpos($siteLocationMall->topList, '第1名'))
            && $this->siteLocationModel->star >= 4
            && $this->siteLocationModel->shopTotalNum >= 40
            && $this->siteLocationModel->facilitiesRating >= 7.8
            && $this->siteLocationModel->environmentRating >= 7.8
            && $this->siteLocationModel->serviceRating >= 7.8
            && $this->siteLocationModel->gourmetShopNum >= 38
            && $this->siteLocationModel->goShoppingNum < 100
            && !strpos($this->siteLocationModel->mallName, '服饰'))
            ||
            (($isInput || strpos($siteLocationMall->topList, '第2名'))
            && $this->siteLocationModel->star >= 4
            && $this->siteLocationModel->shopTotalNum >= 40
            && $this->siteLocationModel->facilitiesRating >= 7.8
            && $this->siteLocationModel->environmentRating >= 7.8
            && $this->siteLocationModel->serviceRating >= 7.8
            && $this->siteLocationModel->gourmetShopNum >= 38
            && $this->siteLocationModel->goShoppingNum >= 100
            && !strpos($this->siteLocationModel->mallName, '服饰'))
            ||
            (($isInput || strpos($siteLocationMall->topList, '第1名'))
            && strpos($this->siteLocationModel->mallName, '奥')
            && strpos($this->siteLocationModel->mallName, '莱')
            && $this->siteLocationModel->facilitiesRating >= 7.8
            && $this->siteLocationModel->environmentRating >= 7.8
            && $this->siteLocationModel->serviceRating >= 7.8
            && !strpos($this->siteLocationModel->mallName, '服饰'))
        ) {
            return [
                'mallGrade' => 'A级',
                'shopGrade' => OpenShopSiteLocationModel::HOUSE_SHOP_GRADE_A
            ];
        }

        if (
            (($isInput || strpos($siteLocationMall->topList, '第2名'))
            && $this->siteLocationModel->star >= 4
            && $this->siteLocationModel->shopTotalNum >= 40
            && $this->siteLocationModel->facilitiesRating >= 7.8
            && $this->siteLocationModel->environmentRating >= 7.8
            && $this->siteLocationModel->serviceRating >= 7.8
            && $this->siteLocationModel->gourmetShopNum >= 38
            && $this->siteLocationModel->goShoppingNum < 100
            && !strpos($this->siteLocationModel->mallName, '服饰'))
            ||
            (($isInput || strpos($siteLocationMall->topList, '第3名'))
            && $this->siteLocationModel->star >= 4
            && $this->siteLocationModel->shopTotalNum >= 40
            && $this->siteLocationModel->facilitiesRating >= 7.8
            && $this->siteLocationModel->environmentRating >= 7.8
            && $this->siteLocationModel->serviceRating >= 7.7
            && $this->siteLocationModel->gourmetShopNum >= 38
            && $this->siteLocationModel->goShoppingNum >= 20
            && !strpos($this->siteLocationModel->mallName, '服饰'))
            ||
            (($isInput || strpos($siteLocationMall->topList, '第4名'))
            && $this->siteLocationModel->star >= 4
            && $this->siteLocationModel->shopTotalNum >= 40
            && $this->siteLocationModel->facilitiesRating >= 7.8
            && $this->siteLocationModel->environmentRating >= 7.8
            && $this->siteLocationModel->serviceRating >= 7.8
            && $this->siteLocationModel->gourmetShopNum >= 38
            && $this->siteLocationModel->goShoppingNum >= 100
            && !strpos($this->siteLocationModel->mallName, '服饰'))
            ||
            (($isInput || strpos($siteLocationMall->topList, '第5名'))
            && $this->siteLocationModel->star >= 4
            && $this->siteLocationModel->shopTotalNum >= 40
            && $this->siteLocationModel->facilitiesRating >= 7.8
            && $this->siteLocationModel->environmentRating >= 7.8
            && $this->siteLocationModel->serviceRating >= 7.8
            && $this->siteLocationModel->gourmetShopNum >= 38
            && $this->siteLocationModel->goShoppingNum >= 100
            && !strpos($this->siteLocationModel->mallName, '服饰'))
            ||
            (($isInput || strpos($siteLocationMall->topList, '第2名'))
            && strpos($this->siteLocationModel->mallName, '奥')
            && strpos($this->siteLocationModel->mallName, '莱')
            && $this->siteLocationModel->facilitiesRating >= 7.8
            && $this->siteLocationModel->environmentRating >= 7.8
            && $this->siteLocationModel->serviceRating >= 7.8
            && !strpos($this->siteLocationModel->mallName, '服饰'))
            ||
            (($isInput || strpos($siteLocationMall->topList, '第3名'))
            && strpos($this->siteLocationModel->mallName, '奥')
            && strpos($this->siteLocationModel->mallName, '莱')
            && $this->siteLocationModel->facilitiesRating >= 7.8
            && $this->siteLocationModel->environmentRating >= 7.8
            && $this->siteLocationModel->serviceRating >= 7.8
            && !strpos($this->siteLocationModel->mallName, '服饰'))
            ||
            (($isInput || strpos($siteLocationMall->topList, '第4名'))
            && strpos($this->siteLocationModel->mallName, '奥')
            && strpos($this->siteLocationModel->mallName, '莱')
            && $this->siteLocationModel->facilitiesRating >= 7.8
            && $this->siteLocationModel->environmentRating >= 7.8
            && $this->siteLocationModel->serviceRating >= 7.8
            && !strpos($this->siteLocationModel->mallName, '服饰'))
        ) {
            return [
                'mallGrade' => 'B级',
                'shopGrade' => OpenShopSiteLocationModel::HOUSE_SHOP_GRADE_B
            ];
        }
        return [
            'mallGrade' => 'C级',
            'shopGrade' => OpenShopSiteLocationModel::HOUSE_SHOP_GRADE_C
        ];
    }

    //更新门店或者房源的附近预展点位
    public function updateNearbyPlaceHolder()
    {
        //如果已完成  就不更新附近信息
        if ($this->siteLocationModel->siteStatus == OpenShopSiteLocationModel::SITE_STATUS_4) {
            return $this->siteLocationModel;
        }
        $nearbyPlaceHolder = AreaService::getAreaCodeByArea($this->siteLocationModel->longitude, $this->siteLocationModel->latitude);
        $obj = new OpenShopSiteLocationModel;
        $obj->timestamps = false;
        $obj->where('id', $this->siteLocationModel->id)->update([
            'nearbyPlaceHolderId'    => $nearbyPlaceHolder['nearbyPlaceHolderId'] ?? 0,
            'nearbyPlaceHolderRange' => $nearbyPlaceHolder['nearbyPlaceHolderRange'] ?? 0,
            'placeholderTime'        => $nearbyPlaceHolder['nearbyPlaceholderTime'] ? strtotime($nearbyPlaceHolder['nearbyPlaceholderTime']) : 0,
            'nearbyShopCode'         => $nearbyPlaceHolder['code'] ?? 0,
            'nearbyRange'            => $nearbyPlaceHolder['distance'] ?? 0,
        ]);
        return $this->siteLocationModel;
    }

}
